import datetime
import json
import os
import random

import requests


def save_data_from_cookie(Cookie):
    # 选课结果
    post_header = {"Cookie": Cookie}
    url = "http://jwcxk2.aufe.edu.cn/student/courseSelect/thisSemesterCurriculum/callback"
    text_url = requests.get(url, headers=post_header).json()
    with open("选课结果.json", "w", encoding='utf-8') as f:
        json.dump(text_url, f)
        # print("选课结果.json保存文件完成...")
        f.close()


def json_read_to_data_json():
    with open("选课结果.json", 'r') as load_f:
        xkjg = json.load(load_f)
        load_f.close()
    return xkjg


def get_weekday_startime_endtime_from_classDay_classSessions_continuingSession(classDay, classSessions,
                                                                               continuingSession):
    startime_list = ["0800", "0855", "1010", "1105", "1400", "1455", "1610", "1705", "1900", "1955"]
    endtime_list = ["0845", "0940", "1055", "1150", "1445", "1540", "1655", "1750", "1945", "2040"]
    weekday = classDay
    startime = startime_list[int(classSessions) - 1]
    endtime = endtime_list[int(classSessions) + int(continuingSession) - 2]
    weekday_startime_endtime = str(weekday) + "#" + str(startime) + "#" + str(endtime)
    return weekday_startime_endtime


def processing_data(usedata):
    class_num = len(list(usedata["xkxx"][0].keys()))
    class_str_list = list(usedata["xkxx"][0].keys())

    class_info_list = []

    for i in range(class_num):
        temp_class_info = usedata["xkxx"][0][str(class_str_list[i])]

        teacher_name = temp_class_info["attendClassTeacher"]  # 赵艳红*
        courseName = temp_class_info["courseName"]  # 软件算法设计综合实训

        teacher_course = str(teacher_name) + "#" + str(courseName) + "#" + str(class_str_list[i])

        didian_num = len(temp_class_info["timeAndPlaceList"])
        timeAndPlaceList = temp_class_info["timeAndPlaceList"]
        time_didian_list = []

        for o in range(didian_num):
            temp_time_list = timeAndPlaceList[o]

            classDay = temp_time_list["classDay"]  # 7 星期几
            classSessions = temp_time_list["classSessions"]  # 1 第几节课开始
            continuingSession = temp_time_list["continuingSession"]  # 8 （一般都是2） 课程持续的时间
            weekday_startime_endtime = get_weekday_startime_endtime_from_classDay_classSessions_continuingSession(
                classDay, classSessions, continuingSession)

            xiaoqu = temp_time_list["campusName"]  # 龙湖东校区
            teachingBuildingName = temp_time_list["teachingBuildingName"]  # 慎思楼
            classroomName = temp_time_list["classroomName"]  # DJSS3-101
            weekDescription = temp_time_list["weekDescription"]  # 1-18周
            classWeek = temp_time_list["classWeek"]  # 111111111111111111000000

            temp_time_didian = weekday_startime_endtime + "#" + str(xiaoqu) + "#" + str(
                teachingBuildingName) + "#" + str(classroomName) + "#" + str(weekDescription) + "#" + str(classWeek)
            time_didian_list.append(temp_time_didian)

        class_info_list.append([teacher_course, time_didian_list])

    class_info_list_data = []
    for i in class_info_list:
        temp = i[0]
        for_temp = i[1]
        for o in for_temp:
            class_info_list_data.append("{}#{}".format(temp, o))
    return class_info_list_data


def get_ics_wz_list(class_info_list_data, stu_name, first_week_mo="20210301", week_num=21, select_system="2"):
    # select_system 1 -> 安卓 2 -> ios 0 -> 没有选
    ics_start = [
        "BEGIN:VCALENDAR",
        "PRODID:-//Wang Peng//Course Calendar//zh",
        "VERSION:2.0",
        "CALSCALE:GREGORIAN",
        "METHOD:PUBLISH",
        "X-WR-CALNAME:课程表日历",
        "X-WR-TIMEZONE:Asia/Shanghai",
        "X-WR-CALDESC:{}的课程表".format(stu_name)
    ]

    ics_VEVENT = []

    for i in class_info_list_data:
        ics_VEVENT = ics_VEVENT + get_VEVENT_list_from_one_class_data_list(i, select_system=select_system,
                                                                           first_week_mo=first_week_mo,
                                                                           week_num=week_num)

    ics_list_wz = ics_start + ics_VEVENT

    return ics_list_wz


def dateRange(beginDate, week=21, endDate='20991229'):
    dates = []
    dt = datetime.datetime.strptime(beginDate, "%Y%m%d")
    date = beginDate[:]
    while date <= endDate and len(dates) < week * 7:
        dates.append(date)
        dt = dt + datetime.timedelta(1)
        date = dt.strftime("%Y%m%d")
    return dates


def get_VEVENT_list_from_one_class_data_list(one_class_data, select_system, first_week_mo="20210301", week_num=21):
    # one_class_data
    # '张徽燕* #操作系统课程设计#18MT0103_06#2#1010#1150#龙湖东校区#广学楼#DJ2-106 管理科学与工程综合实验室1#双周#010101010101010101000000'
    data_list = dateRange(first_week_mo, week_num)
    one_class_data_list = one_class_data.split("#")
    class_time_start = one_class_data_list[4]
    class_time_end = one_class_data_list[5]
    class_zou_str = one_class_data_list[10]
    class_zou_data = one_class_data_list[9]
    class_day = one_class_data_list[3]
    no3 = ""
    no5 = ""
    no_x = ""

    if "-" in class_zou_data:
        # 1-16周的情况
        week_start_no = int(class_zou_data.split("-")[0]) - 1
        class_day_strart = data_list[week_start_no * 7 + int(class_day) - 1]
        nums = 0
        for i, element in enumerate(list(class_zou_str)):
            if element == "1":
                nums = nums + 1
        week_nums = nums
        class_time_start = one_class_data_list[4]
        class_time_end = one_class_data_list[5]
        # select_system 1 -> 安卓 2 -> ios
        if select_system == "2" or select_system == 2:
            no3 = "DTSTART;TZID=Asia/Shanghai:{}T{}00".format(class_day_strart, class_time_start)
            no5 = "DTEND;TZID=Asia/Shanghai:{}T{}00".format(class_day_strart, class_time_end)
        else:
            no3 = "DTSTART:{}T{}00Z".format(class_day_strart, class_time_start)
            no5 = "DTEND:{}T{}00Z".format(class_day_strart, class_time_end)
        no_x = "RRULE:FREQ=WEEKLY;INTERVAL=1;COUNT={}".format(week_nums)
    elif "第" in class_zou_data:
        # 第5周的情况
        week_start_no = int(class_zou_data[1:].split("周")[0]) - 1
        class_day_strart = data_list[week_start_no * 7 + int(class_day) - 1]
        class_time_start = one_class_data_list[4]
        class_time_end = one_class_data_list[5]
        # select_system 1 -> 安卓 2 -> ios
        if select_system == "2" or select_system == 2:
            no3 = "DTSTART;TZID=Asia/Shanghai:{}T{}00".format(class_day_strart, class_time_start)
            no5 = "DTEND;TZID=Asia/Shanghai:{}T{}00".format(class_day_strart, class_time_end)
        else:
            no3 = "DTSTART:{}T{}00Z".format(class_day_strart, class_time_start)
            no5 = "DTEND:{}T{}00Z".format(class_day_strart, class_time_end)
    else:
        # 单双周的情况
        # 双周#010101010101010101000000
        week_start_no = 0
        nums = 0
        for i, element in enumerate(list(class_zou_str)):
            if element == "1":
                nums = nums + 1
            if week_start_no == 0 and element == "1":
                week_start_no = i

        class_day_strart = data_list[week_start_no * 7 + int(class_day) - 1]
        week_nums = nums
        class_time_start = one_class_data_list[4]
        class_time_end = one_class_data_list[5]
        # select_system 1 -> 安卓 2 -> ios
        if select_system == "2" or select_system == 2:
            no3 = "DTSTART;TZID=Asia/Shanghai:{}T{}00".format(class_day_strart, class_time_start)
            no5 = "DTEND;TZID=Asia/Shanghai:{}T{}00".format(class_day_strart, class_time_end)
        else:
            no3 = "DTSTART:{}T{}00Z".format(class_day_strart, class_time_start)
            no5 = "DTEND:{}T{}00Z".format(class_day_strart, class_time_end)

        no_x = "RRULE:FREQ=WEEKLY;INTERVAL=2;COUNT={}".format(week_nums)

    no1 = "BEGIN:VEVENT"

    if "-" not in one_class_data_list[8]:
        one_class_data_list[8] = "a-" + one_class_data_list[8]
    class_didian = "{}_{}".format(one_class_data_list[7], one_class_data_list[8].split("-")[1])
    no2 = "LOCATION:" + class_didian

    class_SUMMARY = one_class_data_list[1]
    no4 = "SUMMARY:{}".format(class_SUMMARY)

    teacher_name = one_class_data_list[0]
    class_no = one_class_data_list[2]
    no6 = "DESCRIPTION:{}_{}".format(teacher_name, class_no)

    no7 = "UID:{}".format(one_class_data)

    no8 = "END:VEVENT"

    ics_VEVENT = []
    if no_x != "":
        ics_VEVENT = [no1, no2, no3, no4, no5, no6, no7, no_x, no8]
    else:
        ics_VEVENT = [no1, no2, no3, no4, no5, no6, no7, no8]

    return ics_VEVENT


def get_ics_file_from_list(ics_list_wz, system_str="IOS"):
    file_name = "{}_{}_kcb.ics".format(random.randint(1000000, 9999999), system_str)
    if os.path.exists(file_name):
        os.remove(file_name)
    os.remove("选课结果.json")
    with open(file_name, "a", encoding="utf-8") as f:
        for i in ics_list_wz:
            f.write("{}\n".format(i))
    return file_name
